package com.example.his.api.mis.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.bean.BeanUtil;
import com.example.his.api.common.PageUtils;
import com.example.his.api.common.R;
import com.example.his.api.mis.controller.form.permission.DeletePermissionForm;
import com.example.his.api.mis.controller.form.permission.InsertPermissionForm;
import com.example.his.api.mis.controller.form.permission.SearchPermissionByPageForm;
import com.example.his.api.mis.controller.form.permission.UpdatePermissionForm;
import com.example.his.api.mis.service.PermissionService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController("MisPermissionController")
@RequestMapping("/mis/permission")
public class PermissionController {
  @Resource
  private PermissionService permissionService;
  
  
  @PostMapping("/insert")
  @SaCheckPermission(value = { "ROOT", "PERMISSION:INSERT" }, mode = SaMode.OR)
  public R insert(@RequestBody @Valid InsertPermissionForm form) {
    int id = permissionService.insert(BeanUtil.beanToMap(form));
    
    return R.ok().put("result", id);
  }
  
  @PostMapping("/deleteByIds")
  @SaCheckPermission(value = { "ROOT", "PERMISSION:DELETE" }, mode = SaMode.OR)
  public R deleteByIds(@RequestBody @Valid DeletePermissionForm form) {
    int rows = permissionService.deleteByIds(form.getIds());
    
    return R.ok().put("result", rows);
  }
  
  @PostMapping("/update")
  @SaCheckPermission(value = { "ROOT", "PERMISSION:UPDATE" }, mode = SaMode.OR)
  public R update(@RequestBody @Valid UpdatePermissionForm form) {
    boolean bool = permissionService.update(BeanUtil.beanToMap(form));
    
    return R.ok().put("result", bool);
  }
  
  @GetMapping("/searchById/{id}")
  @SaCheckPermission(value = { "ROOT", "PERMISSION:SELECT" }, mode = SaMode.OR)
  public R searchById(@PathVariable("id") Integer id) {
    HashMap permission = permissionService.searchById(id);
    
    return R.ok().put("result", permission);
  }
  
  @PostMapping("/searchByPage")
  @SaCheckPermission(value = { "ROOT", "PERMISSION:SELECT" }, mode = SaMode.OR)
  public R searchByPage(@RequestBody @Valid SearchPermissionByPageForm form) {
    Integer page = form.getPage();
    Integer length = form.getLength();
    int start = (page - 1) * length;
    Map param = BeanUtil.beanToMap(form);
    param.put("start", start);
    
    PageUtils pageUtils = permissionService.searchByPage(param);
    
    return R.ok().put("result", pageUtils);
  }
  
  @GetMapping("/searchAll")
  @SaCheckPermission(value = { "ROOT", "PERMISSION:SELECT" }, mode = SaMode.OR)
  public R searchAll() {
    ArrayList <HashMap> list = permissionService.searchAll();
    return R.ok().put("result", list);
  }
  
  
}
